package com.afc.struts.bustle.data;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Vector;

import javax.xml.bind.annotation.XmlRootElement;

import org.apache.commons.beanutils.BeanUtils;

import com.afc.struts.bustle.commons.JsonParser;
import com.afc.struts.bustle.commons.Mapper;
import com.afc.struts.bustle.commons.RestDtoDaoProxy;
import com.afc.struts.bustle.commons.http.TypeToJsonHttpConverter;
import com.afc.struts.bustle.model.ProviderDto;

public class ProviderDao extends RestDtoDaoProxy<Integer, ProviderDto>
{
  public ProviderDao()
  {
    super("localhost", 8080, "provider", new JsonParser(), new TypeToJsonHttpConverter<>(ProviderDto.class), ProviderDto.class, new Mapper<ProviderDto, ProviderDto>()
      {
        @Override
        public ProviderDto map(ProviderDto aSource, ProviderDto aDestination)
        {
          try
          {
            BeanUtils.copyProperties(aDestination, aSource);
          }
          catch (IllegalAccessException | InvocationTargetException anException)
          {
            throw new RuntimeException("Unable copy ProviderDto " + aSource, anException);
          }
          return aDestination;
        }
      });
  }

  @Override
  protected List<ProviderDto> retrieveAllFrom(String aResult)
  {
    return parser.parse(ProviderDtoList.class, aResult).getProvider();
  }

  static public ProviderDao getInstance()
  {
    return INSTANCE;
  }

  static private final ProviderDao INSTANCE = new ProviderDao();

  @XmlRootElement(name = "providers")
  static public class ProviderDtoList
  {
    public List<ProviderDto> getProvider()
    {
      return provider;
    }

    public void setProvider(List<ProviderDto> aList)
    {
      provider = aList;
    }

    protected List<ProviderDto> provider = new Vector<>();
  }
}
